package com.taoban.shopdata.thread;

import java.io.File;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.TermVector;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.TermFreqVector;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.util.Version;
import org.wltea.analyzer.lucene.IKAnalyzer;

import com.yufei.entity.goods.Goods;
import com.yufei.pfw.service.PfwService;
import com.yufei.pfw.service.QueryPaire;
import com.yufei.pfw.service.QueryServiceExcetion;
import com.yufei.utils.SpringUtils;

public class GoodsIndexThread implements Runnable{
	private static final Log mLog = LogFactory.getLog(GoodsIndexThread.class);
	PfwService pfwService=(PfwService) SpringUtils.getBeanFromBeanContainer(PfwService.class);

private List<String> goodsIdList=null;
	public GoodsIndexThread() {
		super();
		// TODO Auto-generated constructor stub
	}

	public GoodsIndexThread(List<String> goodsIdList) {
		super();
		this.goodsIdList = goodsIdList;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		Goods indexGoods=null;
		for(String goodsId:goodsIdList){
			List<QueryPaire> queryPaires=new ArrayList<>();
			String mallItemId = goodsId;
			queryPaires.add(new QueryPaire("mallItemId", "is:"+mallItemId+""));
			try {
				indexGoods=pfwService.query(queryPaires, Goods.class).get(0);
			} catch (QueryServiceExcetion e) {
				// TODO Auto-generated catch block
				continue;
			}
			index(mallItemId, indexGoods.getTitle()+indexGoods.getDesc());
			
		}
	}
	private void index(String mallItemId,String detailDes){
		//建立内存索引对象
		Analyzer analyzer = new IKAnalyzer();
		 
		
		Directory directory = null;
		IndexWriter iwriter = null;
		try {
			directory =FSDirectory.open(new File("D:\\index"));
		
 	 
		
		//配置IndexWriterConfig
		IndexWriterConfig iwConfig = new IndexWriterConfig(Version.LUCENE_36 , analyzer);
		iwConfig.setOpenMode(OpenMode.CREATE_OR_APPEND);
		iwriter = new IndexWriter(directory , iwConfig);
		//写入索引
		Document doc = new Document();
		doc.add(new Field("mallItemId", mallItemId, Field.Store.YES, Field.Index.NOT_ANALYZED));
		Field field =new Field("des", detailDes, Field.Store.YES, Field.Index.ANALYZED,TermVector.YES); //new Field(fieldName, text, Field.Store.YES, Field.Index.ANALYZED);
		System.out.print(field.isTermVectorStored());
		doc.add(field);
		iwriter.addDocument(doc);
		iwriter.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(directory != null){
				try {
					directory.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
	}
	private List<String> getMallitemIdsByPropertyValue(String fieldName,String propertyKey,String propertyValue){
		List<String> mallItemIds=new ArrayList<>();
		IndexReader ireader = null;
		IndexSearcher isearcher = null;
		Analyzer analyzer = new IKAnalyzer();
		Directory directory=null;
		try {
			directory= FSDirectory.open(new File("D:\\index"));
			//搜索过程**********************************
		    //实例化搜索器   
			ireader = IndexReader.open(directory);
			isearcher = new IndexSearcher(ireader);			
			
			//使用QueryParser查询分析器构造Query对象
			QueryParser qp = new QueryParser(Version.LUCENE_36, fieldName, analyzer);
			qp.setDefaultOperator(QueryParser.AND_OPERATOR);
			Query query = qp.parse(propertyValue);
			
			//搜索相似度最高的5条记录
			TopDocs topDocs = isearcher.search(query , 3000);
			System.out.println("命中：" + topDocs.totalHits);
			//输出结果
			ScoreDoc[] scoreDocs = topDocs.scoreDocs;
			TermFreqVector termFreqVector;
			for (int i = 0; i < topDocs.totalHits; i++){
				Document targetDoc = isearcher.doc(scoreDocs[i].doc);
				mallItemIds.add(targetDoc.get("mallItemId"));
				/*termFreqVector=ireader.getTermFreqVector(scoreDocs[i].doc, fieldName);
				String[] terms=termFreqVector.getTerms();
				int[] freqs=termFreqVector.getTermFrequencies();
				for(int j=0;j<terms.length;j++){
					System.out.print(terms[j]+":"+freqs[j]+"\n");
				}
				*/
				//System.out.println("内容：" + targetDoc.toString());
			}			
			


		
		}catch(Exception e){
			
		}finally{
			if(ireader != null){
				try {
					ireader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return mallItemIds;
	}
public static void main(String[] args){
	PfwService pfwService=(PfwService) SpringUtils.getBeanFromBeanContainer(PfwService.class);
	/*try {
		 List<Goods> goodses=pfwService.query(new ArrayList(), Goods.class);
		 mLog.info(goodses.size());
		 List<String> mallIds=new ArrayList<>();
		 for(Goods goods:goodses){
			 mallIds.add(goods.getMallItemId());
		 }
		 new GoodsIndexThread(mallIds).run();
		 
	} catch (QueryServiceExcetion e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}*/
	
	GoodsIndexThread goodsIndexThread= new GoodsIndexThread(null);
	/*List<String> mallIds=goodsIndexThread.getMallitemIdsByPropertyValue("des", "cpu", "i5");
	mLog.info(mallIds.size());*/
	List<String> mallIds=null;
//	mallIds=goodsIndexThread.getMallitemIdsByPropertyValue("des", "cpu", "集显 独显");
	//mLog.info(mallIds.size());
	mallIds=goodsIndexThread.getMallitemIdsByPropertyValue("des", "cpu", "1g独显");
	mLog.info(mallIds.size());
	mallIds=goodsIndexThread.getMallitemIdsByPropertyValue("des", "cpu", "2g独显");
	mLog.info(mallIds.size());
	mallIds=goodsIndexThread.getMallitemIdsByPropertyValue("des", "cpu", "1g独立显卡");
	mLog.info(mallIds.size());
	mallIds=goodsIndexThread.getMallitemIdsByPropertyValue("des", "cpu", "2g独立显卡");
	mLog.info(mallIds.size());
	
			
	
}
}
